/*
 * Created by JFormDesigner on Wed Aug 20 20:08:07 CST 2025
 */

package org.xl.main.jenkins;

import cn.hutool.core.util.StrUtil;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.swing.*;

/**
 * @author Windows
 */
public class JenkinsDeployFrame extends JFrame {
    public JenkinsDeployFrame() {
        initComponents();
    }

    private void modifiedPasswordOk(ActionEvent e) {
        // TODO add your code here
        SwingUtilities.invokeLater(() -> {
            UserPwdChangeFrame userPwdChangeFrame = new UserPwdChangeFrame();
            userPwdChangeFrame.setSize(400,300);
            userPwdChangeFrame.setVisible(true);
            userPwdChangeFrame.setLocationRelativeTo(null);
            userPwdChangeFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        });

    }

    private void bushuBtnOk(ActionEvent e) {
        JenkinsDeployFrame jenkinsDeployFrame = this;
        SwingWorker bushuWorker = new SwingWorker() {
           @Override
            protected Object doInBackground() throws Exception {
               try {
                   // TODO add your code here
                   Properties properties = new Properties();
                   properties.load(this.getClass().getClassLoader().getResourceAsStream("config/jenkins_user.properties"));
                   String username = (String)properties.get("userName");
                   String jenkinsUrl = (String)properties.get("jenkinsHost");
                   String apiToken = (String)properties.get("apiToken");
                   String projectSuffix = (String)properties.get("projectSuffix");
                   String buildParams = (String)properties.get("buildParams");
                   String jobName =  getProjectName(properties);
                   String buildNumber = "lastBuild"; // 构建号
                   JenkinsJobTrigger trigger = new JenkinsJobTrigger(jenkinsUrl,projectSuffix, username, apiToken, 10);

                   //  触发带参数Job
                   Map<String, Object> parameters = new HashMap<>();
                   if (StrUtil.isNotEmpty(buildParams)) {
                       for (String params : buildParams.split("#")) {
                           String[] allParams = params.split("=");
                           parameters.put(allParams[0], allParams[1]);
                       }
                   }
                   int queueId2 = trigger.triggerJobWithCrumb(jobName, parameters, "Automated build triggered by API");
                   JOptionPane.showMessageDialog(jenkinsDeployFrame,"触发成功，队列ID: " + queueId2);
                   Thread.sleep(1500);
                   qbrzBtnOk(null);

               } catch (IOException ex) {
                   JOptionPane.showInternalMessageDialog(jenkinsDeployFrame,"触发失败 " + ex.getMessage());
               }
               return null;
           }
       };
       bushuWorker.execute();
    }

    private String getProjectName(Properties properties) {
        String projectList = (String) properties.get("projectList");
        String[] projectInfos = projectList.split(",");
        int selectedIndex = comboBox1.getSelectedIndex();
        String projectName = "";
        for (int i = 0; i < projectInfos.length; i++) {
            if (selectedIndex == i) {
                projectName = projectInfos[i].split("#")[1];
            }
        }
        return projectName;
    }

    private void setComboBox1Value(JComboBox<String> comboBox1) {
        try {
            Properties properties = new Properties();
            properties.load(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("config/jenkins_user.properties"), StandardCharsets.UTF_8));
            String projectList = (String) properties.get("projectList");
            String[] projectInfos = projectList.split(",");
            String[] checkOptions = new String[projectInfos.length];
            for (int i = 0; i < projectInfos.length; i++) {
                checkOptions[i] = projectInfos[i].split("#")[0];
            }
            comboBox1.setModel(new DefaultComboBoxModel(checkOptions));
        } catch (IOException e) {

        }

    }

    private void ssriBtnOk(ActionEvent e) {
        // TODO add your code
        SwingWorker ssriWorker = new SwingWorker() {
            @Override
            protected Object doInBackground() throws Exception {
                try {
                    Properties properties = new Properties();
                    properties.load(this.getClass().getClassLoader().getResourceAsStream("config/jenkins_user.properties"));
                    String username = (String)properties.get("userName");
                    String jenkinsUrl = (String)properties.get("jenkinsHost");
                    String apiToken = (String)properties.get("apiToken");
                    String projectSuffix = (String)properties.get("projectSuffix");
                    String jobName =  getProjectName(properties);
                    String buildNumber = "lastBuild"; // 构建号
                    JenkinsJobTrigger trigger = new JenkinsJobTrigger(jenkinsUrl,projectSuffix, username, apiToken, 10);
                    trigger.streamConsoleLog(jobName, buildNumber, log -> {
                        textArea1.setText(textArea1.getText() + log);
                    }, 1000);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                return null;
            }
        };
        ssriWorker.execute();


    }

    private void qbrzBtnOk(ActionEvent e) {
        // TODO add your code here
        SwingWorker qbrzWorker = new SwingWorker() {
            @Override
            protected Object doInBackground() throws Exception {
                try {
                    Properties properties = new Properties();
                    properties.load(this.getClass().getClassLoader().getResourceAsStream("config/jenkins_user.properties"));
                    String username = (String)properties.get("userName");
                    String jenkinsUrl = (String)properties.get("jenkinsHost");
                    String apiToken = (String)properties.get("apiToken");
                    String projectSuffix = (String)properties.get("projectSuffix");
                    String jobName =  getProjectName(properties);
                    String buildNumber = "lastBuild"; // 构建号
                    JenkinsJobTrigger trigger = new JenkinsJobTrigger(jenkinsUrl,projectSuffix, username, apiToken, 10);
                    String fullConsoleLog = trigger.getFullConsoleLog(jobName, buildNumber);
                    textArea1.setForeground(Color.BLUE);
                    textArea1.setText(fullConsoleLog);
                } catch (IOException ex) {

                }
                return null;
            }
        };
        qbrzWorker.execute();
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        label1 = new JLabel();
        scrollPane1 = new JScrollPane();
        textArea1 = new JTextArea();
        textField1 = new JTextField();
        comboBox1 = new JComboBox<>();
        button6 = new JButton();
        button1 = new JButton();

        //======== this ========
        Container contentPane = getContentPane();
        contentPane.setLayout(null);

        //---- label1 ----
        label1.setText("\u5f53\u524d\u7528\u6237: huanglong1");
        contentPane.add(label1);
        label1.setBounds(80, 5, 124, 17);

        //======== scrollPane1 ========
        {
            scrollPane1.setViewportView(textArea1);
        }
        contentPane.add(scrollPane1);
        scrollPane1.setBounds(0, 115, 1900, 800);

        //---- textField1 ----
        textField1.setText("\u8bf7\u9009\u62e9\u4f60\u9700\u8981\u90e8\u7f72\u7684\u9879\u76ee:");
        contentPane.add(textField1);
        textField1.setBounds(75, 35, 155, 30);

        //---- comboBox1 ----
        comboBox1.setToolTipText("tertewr");
        comboBox1.setModel(new DefaultComboBoxModel<>(new String[] {
            "1:\u8fd0\u884c\u98ce\u9669",
            "2:\u4e8c\u6b21\u7cfb\u7edf",
            "3:\u8fd0\u884c\u8ba1\u5212",
            "4:\u5e76\u7f51\u7ba1\u7406",
            "5:\u8fd0\u884c\u63a7\u5236"
        }));
        setComboBox1Value(comboBox1);
        comboBox1.setSelectedIndex(0);
        contentPane.add(comboBox1);
        comboBox1.setBounds(255, 40, 125, 25);

        //---- button6 ----
        button6.setText("\u5237\u65b0\u65e5\u5fd7");
        button6.addActionListener(e -> qbrzBtnOk(e));
        contentPane.add(button6);
        button6.setBounds(450, 40, 104, 25);

        //---- button1 ----
        button1.setText("deploy");
        button1.addActionListener(e -> bushuBtnOk(e));
        contentPane.add(button1);
        button1.setBounds(240, 85, 80, button1.getPreferredSize().height);

        {
            // compute preferred size
            Dimension preferredSize = new Dimension();
            for(int i = 0; i < contentPane.getComponentCount(); i++) {
                Rectangle bounds = contentPane.getComponent(i).getBounds();
                preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
            }
            Insets insets = contentPane.getInsets();
            preferredSize.width += insets.right;
            preferredSize.height += insets.bottom;
            contentPane.setMinimumSize(preferredSize);
            contentPane.setPreferredSize(preferredSize);
        }
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JLabel label1;
    private JScrollPane scrollPane1;
    private JTextArea textArea1;
    private JTextField textField1;
    private JComboBox<String> comboBox1;
    private JButton button6;
    private JButton button1;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
}
